package entity;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author Francis
 */
public class EntityManagerHelper {

    private static final ThreadLocal<EntityManager> threadLocal = new ThreadLocal<EntityManager>();
    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("2handdb");

    public static EntityManagerFactory getFactory() {
        return Persistence.createEntityManagerFactory("2handdb");
    }

    public static EntityManager getEntityManager() {
        EntityManager em = threadLocal.get();
        if (em == null) {
            em = emf.createEntityManager();
            threadLocal.set(em);
        }
        return em;
    }

    public static boolean persist(Object object, EntityManagerFactory emf) {
        EntityManager em = emf.createEntityManager();
        boolean result = false;
        try {
            em.getTransaction().begin();
            em.persist(object);
            em.getTransaction().commit();
            result = true;
        } catch (Exception e) {
            java.util.logging.Logger.getLogger(PersonService.class.getName()).log(java.util.logging.Level.SEVERE, "Persistence Error", e);
            em.getTransaction().rollback();
        } finally {
            em.close();
        }
        return result;
    }

    public static boolean merge(Object object, EntityManagerFactory emf) {
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.merge(object);
            em.getTransaction().commit();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            em.close();
        }
        return false;
    }
}
